package hk.ust.cse.comp3111.studentSchedule;

import android.app.Activity;
import android.app.DialogFragment;
import android.app.Fragment;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.CalendarContract;
import android.support.v4.app.FragmentTransaction;
import android.text.format.Time;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;










import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.view.View.OnClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.app.TimePickerDialog;
import android.widget.TimePicker;





public class AddEvent extends Fragment implements OnClickListener{
	
	public AddEvent(){}
	
	EditText etStartDate, etEndDate, etStartTime, etEndTime, etitle, elocation, edescription;
	Button add;
	TextView textssssss;
	long calendarID;
	long eventID;
	Spinner courseSelectSpinner;
	
	CourseDatabaseHandler db;
	
	@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
 
        View rootView = inflater.inflate(R.layout.add_event, container, false);
        
        return rootView;
    }
	
	@Override
	public void onStart() {
		super.onStart();
		add = (Button)this.getView().findViewById(R.id.buttonadd);
        add.setOnClickListener(this);
		etStartDate = (EditText)this.getView().findViewById(R.id.editStartDate);
		etStartDate.setOnClickListener((OnClickListener) this);
		etEndDate = (EditText)this.getView().findViewById(R.id.editEndDate);
		etEndDate.setOnClickListener((OnClickListener) this);
		etStartTime = (EditText)this.getView().findViewById(R.id.editStartTime);
		etStartTime.setOnClickListener((OnClickListener) this);
		etEndTime = (EditText)this.getView().findViewById(R.id.editEndTime);
		etEndTime.setOnClickListener((OnClickListener) this);
		etitle = (EditText)this.getView().findViewById(R.id.etitle);
		etitle.setOnClickListener((OnClickListener) this);
		elocation = (EditText)this.getView().findViewById(R.id.elocation);
		elocation.setOnClickListener((OnClickListener) this);
		edescription = (EditText)this.getView().findViewById(R.id.edescription);
		courseSelectSpinner = (Spinner) this.getView().findViewById(R.id.courseSelectSpinner);
		edescription.setOnClickListener((OnClickListener) this);
		

		

		
	}
	
	
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
        case R.id.editStartDate:
        	setStartDate();
            break;
        case R.id.editEndDate:
        	setEndDate();
            break;
        case R.id.editStartTime:
        	setStartTime();
        	break;
        case R.id.editEndTime:
        	setEndTime();
        	break;
        case R.id.buttonadd:
        	addEvent();
            break;
        }   
		
	}
	

	private void setStartDate() {
		Calendar calendar = Calendar.getInstance();
		new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener(){
			@Override
			public void onDateSet(DatePicker view, int year, int month, int day){
				etStartDate.setText(year+"/"+(month+1)+"/"+day);
			}
		},calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
	}
	
	private void setEndDate() {
		Calendar calendar = Calendar.getInstance();
		new DatePickerDialog(getActivity(), new DatePickerDialog.OnDateSetListener(){
			@Override
			public void onDateSet(DatePicker view, int year, int month, int day){
				etEndDate.setText(year+"/"+(month+1)+"/"+day);
			}
		},calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH)).show();
	}
	
	private void setStartTime(){
		Calendar calendar = Calendar.getInstance();
		new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener(){
			@Override
			public void onTimeSet(TimePicker view, int hour, int min){
				etStartTime.setText(String.format("%02d:%02d", hour,min));
			}
		},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
	}
	
	private void setEndTime(){
		Calendar calendar = Calendar.getInstance();
		new TimePickerDialog(getActivity(), new TimePickerDialog.OnTimeSetListener(){
			@Override
			public void onTimeSet(TimePicker view, int hour, int min){
				etEndTime.setText(String.format("%02d:%02d", hour,min));
			}
		},calendar.get(Calendar.HOUR_OF_DAY),calendar.get(Calendar.MINUTE),true).show();
	}
	
	private void addEvent() {
    	calendarID = getCalendarID();	
    	ContentValues eventValues = new ContentValues ();
    	// provide the required fields for creating an event to
    	// ContentValues instance and insert event using
    	// ContentResolver
    	String startDate = etStartDate.getText().toString();
    	String endDate = etEndDate.getText().toString();
    	String startTime = etStartTime.getText().toString();
    	String endTime = etEndTime.getText().toString();
    	String description = edescription.getText().toString();
    	String location = elocation.getText().toString(); 
    	String details = description + " " + location;
    	if(startDate.matches("") || startTime.matches("") || endDate.matches("") || endTime.matches("")){
    		Toast.makeText(getActivity(),"Fail! Please fill in all the date/time!",Toast.LENGTH_SHORT).show();
    	}
    	else{
    		eventValues.put(CalendarContract.Events.CALENDAR_ID,calendarID);
    		eventValues.put (CalendarContract.Events.TITLE,etitle.getText().toString());
    		eventValues.put (CalendarContract.Events.DESCRIPTION,details);
    		eventValues.put(CalendarContract.Events.DTSTART,getTime(etStartDate,etStartTime));
    		eventValues.put(CalendarContract.Events.DTEND,getTime(etEndDate,etEndTime));
    		eventValues.put(CalendarContract.Events.EVENT_TIMEZONE,TimeZone.getDefault().toString());
    		Uri eventUri = this.getActivity().getContentResolver().insert(CalendarContract.Events.CONTENT_URI, eventValues);
    		eventID = ContentUris.parseId(eventUri);
	    	etStartDate.setText("");
	    	etEndDate.setText("");
	    	etStartTime.setText("");
	    	etEndTime.setText("");
	    	etitle.setText("");
	    	edescription.setText("");
	    	elocation.setText("");
	    	Toast.makeText(getActivity(),"Success!",Toast.LENGTH_SHORT).show();
    	//textssssss.setText("event id "+ eventID +" inserted");
    	}
    }
	
	public long getCalendarID() {
    	Cursor cur = null;
    	try {
    	// provide CalendarContract.Calendars.CONTENT_URI to
    	// ContentResolver to query calendars
    		cur = this.getActivity().getContentResolver().query(CalendarContract.Calendars.CONTENT_URI,null,null,null, null);
    		if (cur.moveToFirst()) {
    			return cur.getLong(cur.getColumnIndex(CalendarContract.Calendars._ID));
    		}
    	} catch (Exception e) {
    		e.printStackTrace();
    		} finally {
		    	if (cur != null) {
		    	cur.close();
		    	}
    		}
    	return -1L;
    	}
    	
	
	//cherry's getTime
	long getTime(EditText date, EditText time){
    	Calendar calendar = Calendar.getInstance();
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd HH:mm");
    	String eventdate = date.getText().toString();
    	String eventtime = time.getText().toString();
    	String datetime = eventdate + " " + eventtime;
    	Date eventdate2;
		try {
			eventdate2 = sdf.parse(datetime);
			calendar.setTime(eventdate2);
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    	int year = calendar.get(Calendar.YEAR);
    	int month = calendar.get(Calendar.MONTH);
    	int day = calendar.get(Calendar.DAY_OF_MONTH);
    	int hour = calendar.get(Calendar.HOUR_OF_DAY);
    	int min = calendar.get(Calendar.MINUTE);
    	calendar.set(year, month, day, 
    			hour, min, 0);
    	long startTime = calendar.getTimeInMillis();
    	return startTime;
    }
	

	
	
	
}


